/*******************************************************************************
 * Copyright (c) 2011 - 2012 TXT e-solutions SpA
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * This work was performed within the IoT_at_Work Project
 * and partially funded by the European Commission's
 * 7th Framework Programme under the research area ICT-2009.1.3
 * Internet of Things and enterprise environments.
 *
 *
 * Authors:
 *     Cristoforo Seccia (TXT e-solutions SpA)
 *
 * Contributors:
 *      Domenico Rotondi (TXT e-solutions SpA)
 *******************************************************************************/
package it.txt.access.capability.wizard;

import it.txt.access.capability.factory.CapabilitySchemaFactoryException;
import it.txt.access.capability.factory.CapabilitySchemaFactory;
import it.txt.access.capability.wizard.panel.descriptor.DescriptorPanelAccessType;
import it.txt.access.capability.wizard.panel.descriptor.DescriptorPanelAccessTypeCapability;
import it.txt.access.capability.wizard.panel.descriptor.DescriptorPanelAccessTypePolicy;
import it.txt.access.capability.wizard.panel.descriptor.DescriptorPanelAssertion;
import it.txt.access.capability.wizard.panel.descriptor.DescriptorPanelKeystore;
import it.txt.access.capability.wizard.panel.descriptor.DescriptorPanelWelcome;
import it.txt.access.capability.wizard.util.Resources;
import it.txt.access.capability.wizard.util.PluginsLoader;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.net.URL;
import java.util.Locale;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;

/**
 * -----------------------------------------------------------------------------
 * Graphical Wizard Application that allows users to create a root authorization
 * capability or a generig capability containing a previously defined one. The a
 * pplication also can be used to verify the validy of a Capability.
 *
 * ******************************************
 *
 * @version 2.0.0
 * @author  http://www.txtgroup.com
 * @author  Cristoforo Seccia (cristoforo.seccia@txtgroup.com)
 * @author Salvatore Piccione (TXT e-solutions SpA - salvatore.piccione AT txtgroup.com)
 * @contributor Domenico Rotondi (domenico.rotongi@txtgroup.com)
 * 
 * -----------------------------------------------------------------------------
 */
public class WizardMainListener implements WindowListener {

    private static final Logger LOGGER = Logger.getLogger(WizardMainListener.class.getName());
    private Wizard wizard;

    public void windowOpened(WindowEvent arg0) {
    }

    public void windowClosed(WindowEvent arg0) {
    }

    public void windowIconified(WindowEvent arg0) {
    }

    public void windowDeiconified(WindowEvent arg0) {
    }

    public void windowActivated(WindowEvent arg0) {
    }

    public void windowDeactivated(WindowEvent arg0) {
    }

    public void windowClosing(WindowEvent event) {

        if (wizard.getReturnCode() == Wizard.FINISH_RETURN_CODE) {
            closeWizardAndExitApplication();
        } else {
            int result = JOptionPane.showConfirmDialog(wizard,
                    "Are you sure you want to close the wizard?");
            if (result == JOptionPane.YES_OPTION) {
                closeWizardAndExitApplication();
            }
        }
    }

    /**
     * Installs the JGoodies Look & Feels, if available, in classpath.
     */
    public final void initializeLookAndFeels() {
        // if in classpath thry to load JGoodies Plastic Look & Feel
        try {
            LookAndFeelInfo[] lnfs = UIManager.getInstalledLookAndFeels();
            boolean found = false;
            for (int i = 0; i < lnfs.length; i++) {
                if (lnfs[i].getName().equals("JGoodies Plastic 3D")) {
                    found = true;
                }
            }
            if (!found) {
                UIManager.installLookAndFeel("JGoodies Plastic 3D",
                        "com.jgoodies.looks.plastic.Plastic3DLookAndFeel");
            }
            UIManager.setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel");
            //UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
            //UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
            //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");            
        } catch (Throwable t) {
            try {
                LOGGER.log(Level.INFO, "Error while setting L&F. Set the system default L&F.");
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void closeWizardAndExitApplication() {
        wizard.setVisible(false);
        wizard.dispose();
        switch (wizard.getReturnCode()) {
            case Wizard.CANCEL_RETURN_CODE: {
                LOGGER.log(Level.WARNING, "Wizard return code Cancel.");
                break;
            }
            case Wizard.ERROR: {
                LOGGER.log(Level.SEVERE, "Wizard return code is Error.");
                break;
            }
            case Wizard.FINISH_RETURN_CODE: {
                LOGGER.log(Level.INFO, "Wizard return code is Finish.");
                break;
            }
        }
        System.exit(0);
    }

    public void createAndShowWizard() throws WizardException {
        initializeLookAndFeels();
        URL iconLogoURL = getClass().getResource(Resources.IMAGES_DIR + "IoT_icon.png");
        wizard = new Wizard();
        wizard.setTitle("IoT@Work - Capability Based Management");
        wizard.setIconImage(new ImageIcon(iconLogoURL).getImage());
        wizard.setDefaultCloseOperation(Wizard.DO_NOTHING_ON_CLOSE);
        WizardPanelDescriptor[] descriptors = new WizardPanelDescriptor[6];
        descriptors[0] = new DescriptorPanelWelcome(wizard, 0);
        descriptors[1] = new DescriptorPanelAccessType(wizard, 1);
        descriptors[2] = new DescriptorPanelAccessTypePolicy(wizard, 2);
        descriptors[3] = new DescriptorPanelAccessTypeCapability(wizard, 3);
        descriptors[4] = new DescriptorPanelKeystore(wizard, 4);
        descriptors[5] = new DescriptorPanelAssertion(wizard, 5);
        wizard.setWizardPanelDescriptors(descriptors);
        wizard.addWindowListener(this);
        wizard.pack();
        wizard.setVisible(true);
    }

    public static void main(String[] args) {
        String pluginsPath = null;
        String schemasPath = null;
        if (args.length < 2) {
            System.err.println("Usage: Plugins Path; Capability Schemas Path.");
            System.exit(1);
        } else {
            pluginsPath = new File(args[0]).getAbsolutePath();
            schemasPath = new File(args[1]).getAbsolutePath();
        }
        System.out.println("Plugins path: " + pluginsPath);
        System.out.println("Schemas path: " + schemasPath);
        Locale.setDefault(Locale.UK);
        WaitFrameController wfc = null;
        try {
            wfc = new WaitFrameController("Access Capability Wizard");
            wfc.displayApplicationLoadingFrame();
            CapabilitySchemaFactory.getInstance(schemasPath);
            LOGGER.log(Level.INFO, "***************************************");
            LOGGER.log(Level.INFO, "Searching for plugins...");
            PluginsLoader.loadAdvailablePlugins(new File(pluginsPath));
            LOGGER.log(Level.INFO, "***************************************");
            if (wfc.isApplicationLoadingFrameVisible()) {
                wfc.closeApplicationLoadingFrame();
            }
            WizardMainListener listener = new WizardMainListener();
            listener.createAndShowWizard();
        } catch (CapabilitySchemaFactoryException ex) {
            if (wfc.isApplicationLoadingFrameVisible()) {
                wfc.closeApplicationLoadingFrame();
            }
            LOGGER.log(Level.SEVERE, null, ex);
        } catch (WizardException ex) {
            if (wfc.isApplicationLoadingFrameVisible()) {
                wfc.closeApplicationLoadingFrame();
            }
            LOGGER.log(Level.SEVERE, null, ex);
        }
    }
}
